//
//  CustomTextField.swift
//  WebSocketDemo
//
//  Created by 姬向阳 on 2020/5/8.
//  Copyright © 2020 SUNNYJ. All rights reserved.
//

import SwiftUI

// 将UITextField封装成SwiftUI的View,解决TextField输入中文显示Bug.
struct CustomTextField: UIViewRepresentable {
    let limit: Int
    let placeholder: String?
    @Binding var text: String
    let onCommit: () -> Void
    
    init(limit: Int = .max, placeholder: String? = nil,text: Binding<String>, onCommit: @escaping () -> Void = {}) {
        self.limit = limit
        self.placeholder = placeholder
        self._text = text
        self.onCommit = onCommit
    }
    
    func makeUIView(context: Context) -> UITextField {
        let view = UITextField()
        view.placeholder = placeholder
        view.text = text
        view.borderStyle = UITextField.BorderStyle.roundedRect
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 4
        view.layer.borderWidth = 1
        view.layer.borderColor = UIColor.black.cgColor
        view.returnKeyType = UIReturnKeyType.send
        view.delegate = context.coordinator
        return view
    }
    
    func updateUIView(_ uiView: UITextField, context: Context) {
        // 清空TextField
        if text == "" {
            uiView.text = text
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject, UITextFieldDelegate {
        var parent: CustomTextField
        
        init(_ view: CustomTextField) {
            parent = view
        }
        
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            if string == "\n" {
                // textField.endEditing(true)
                parent.onCommit()
                return false
            }
            
            guard let currentText = textField.text,
                let currentRange = Range(range, in: currentText) else {
                    return false
            }
            let updatedText = currentText.replacingCharacters(in: currentRange, with: string)
            if updatedText.count <= parent.limit {
                parent.text = updatedText
                return true
            }
            return false
        }
        /*
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            parent.onCommit()
            return true
        }
        
        func textFieldDidChangeSelection(_ textField: UITextField) {
            // 祖传代码,鬼知道为什么这里要使用GCD异步执行,似乎有什么多线程问题?鬼知道,反正这样写就没警告.
            // 详细解释: https://swiftui-lab.com/state-changes/
            print(textField.text ?? "kong string")
            print(textField.text?.count ?? 0)
            print(parent.limit)
            if textField.text?.count ?? 0 < parent.limit {
                DispatchQueue.main.async {
                    self.parent.text = textField.text ?? ""
                }
            }
        }
 */
    }
}

struct CustomTextField_Previews: PreviewProvider {
    static var previews: some View {
        CustomTextField(text: .constant("你好"))
            .frame(height: 22)
    }
}
